package com.javabasic.algorithm.leetcode;

public class MergeTwoSortedLists {

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(-1), index = result;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                index.next = new ListNode(l1.val);
                l1 = l1.next;
            } else {
                index.next = new ListNode(l2.val);
                l2 = l2.next;
            }
            index = index.next;
        }
        if (l1 != null) {
            index.next = l1;
        }
        if (l2 != null) {
            index.next = l2;
        }
        return result.next;
    }

    // 内存优化解法
    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        ListNode result = null, index = null;
        boolean flag = true;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                if (flag) {
                    index = new ListNode(l1.val);
                    result = index;
                    flag = false;
                } else {
                    index.next = new ListNode(l1.val);
                    index = index.next;
                }
                l1 = l1.next;
            } else {
                if (flag) {
                    index = new ListNode(l2.val);
                    result = index;
                    flag = false;
                } else {
                    index.next = new ListNode(l2.val);
                    index = index.next;
                }
                l2 = l2.next;
            }
        }
        if (flag) {
            if (l1 != null) {
                return l1;
            }
            if (l2 != null) {
                return l2;
            }
        } else {
            if (l1 != null) {
                index.next = l1;
            }
            if (l2 != null) {
                index.next = l2;
            }
        }

        return result;
    }
}

// Definition for singly-linked list.
//class ListNode {
//    int val;
//    ListNode next;
//    ListNode(int x) { val = x; }
//}
